package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    /**
     * Get https://api.weixin.qq.com/sns/jscode2session
     * POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
     * GET https://api.weixin.qq.com/cgi-bin/token
     */
    public static final String URL_OPENID="https://api.weixin.qq.com/sns/jscode2session";
    public static final String URL_Phone="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    public static final String URL_ACCESSTOKEN="https://api.weixin.qq.com/cgi-bin/token";

    /**
     * 配置属性
     */
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;


    /**
     * 获取openId
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //1)封装请求参数
        Map<String, Object> dataMap = getRequestParams();
        dataMap.put("js_code",code);
        dataMap.put("grant_type","authorization_code");
        //2)发送请求
        String result = HttpUtil.get(URL_OPENID, dataMap);
        //3)处理响应
        JSONObject jsonObject = JSONUtil.toBean(result, JSONObject.class);
        //4)错误处理
        Integer errcode = jsonObject.getInt("errcode");
        if(errcode!=null && errcode !=0){
            if (errcode==40029){
                throw new BaseException("js_code 无效");
            }else if(errcode==45011){
                throw new BaseException("API 调用太频繁，请稍候再试");
            }else if(errcode==40226){
                throw new BaseException("高风险等级用户，小程序登录拦截 。风险等级详见用户安全解方案");
            }else if(errcode==-1){
                throw new BaseException("系统繁忙，请稍候再试");
            }
        }
        return jsonObject.getStr("openid");
    }

    @NotNull
    private Map<String, Object> getRequestParams() {
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("appid",appId);
        dataMap.put("secret",appSecret);
        return dataMap;
    }

    /**
     * 获取手机号Phone
     * @param code
     * @return
     */
    @Override
    public String getPhone(String code) {
        //1)封装请求参数
        Map<String,Object> dataMap = new HashMap<>();
//        dataMap.put("accsess_token",accessToken());
//        dataMap.put("openid","");
        dataMap.put("code",code);

        //2)发送请求Post
        System.out.println(accessToken());
        HttpResponse response = HttpUtil.createPost(URL_Phone+accessToken())
                .body(JSONUtil.toJsonStr(dataMap))
                .execute();
        System.out.println(response);

        //3)处理响应
        String result = response.body();
        JSONObject jsonObject = JSONUtil.toBean(result, JSONObject.class);
        Object phone = jsonObject.getByPath("phone_info.purePhoneNumber");
        return phone.toString();
    }

    private String accessToken(){
        //1)封装请求参数
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("grant_type","client_credential");
        dataMap.put("appid",appId);
        dataMap.put("secret",appSecret);
        //2)发送请求
        String result = HttpUtil.get(URL_ACCESSTOKEN, dataMap);
        System.out.println(result);
        //3)处理响应
        JSONObject jsonObject = JSONUtil.toBean(result, JSONObject.class);
        //4)错误处理 - 略
        return jsonObject.getStr("access_token");
    }
}
